package com.eight.cloud.payment.config;

import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * 微信支付配置类
 *
 * @ClassName: WechatPaymentConfiguration
 * @Author: TXC
 * @Date: 2024-10-21 16:50
 **/
@Configuration
public class WechatPaymentConfiguration {
    @Resource
    private WechatServiceProviderConfig wechatServiceProviderConfig;

    private static final String API_CLIENT_KEY_PATH = "cert/apiclient_key.pem";
    @Bean
    public RSAAutoCertificateConfig rsaAutoCertificateConfig() {
        return new RSAAutoCertificateConfig.Builder()
                .merchantId(wechatServiceProviderConfig.getMerchantId())
                .privateKey(getResourceFileContent())
                .merchantSerialNumber(wechatServiceProviderConfig.getMerchantSerialNumber())
                .apiV3Key(wechatServiceProviderConfig.getApiV3Key())
                .build();
    }

    /**
     * 读取资源文件
     *
     * @return 文件内容
     */
    private static String getResourceFileContent() {
        InputStream publicKeyStream = WechatPaymentConfiguration.class.getClassLoader().getResourceAsStream(WechatPaymentConfiguration.API_CLIENT_KEY_PATH);
        if (publicKeyStream == null) {
            throw new RuntimeException("file not found: " + WechatPaymentConfiguration.API_CLIENT_KEY_PATH);
        }
        try (BufferedReader br = new BufferedReader(new InputStreamReader(publicKeyStream))) {
            StringBuilder str = new StringBuilder();
            br.lines().forEach(line -> str.append(line).append("\n"));
            return str.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
